<template>
  <div></div>
  <div :style="'transform:translate('+props.x+'px,'+props.y+'px);width:'+props.width+'px;height:'+props.height+'px;'+'opacity:'+props.opacity+';'" id="AiHumanPM" class="AiHumanPM"></div>
</template>
<script setup lang="ts">
import {driveUeApi } from "@/api/apiRequst"

import {mittTypes} from "@/util/types"
import {driveUeWebsocket} from "./scripts/websocket.js"
// import * as AiHumanPMSDK from "./scripts/AiHumanPM_v1.3.0.js"
import { ref,onMounted,defineEmits,getCurrentInstance } from 'vue'
import {useSceneStore} from '@/stores/scene';
const sceneStore = useSceneStore()
const {appContext: {config: {globalProperties}}} = getCurrentInstance();

const internalInstance = getCurrentInstance()
const emitter = internalInstance.appContext.config.globalProperties.emitter
const origin = internalInstance.appContext.config.globalProperties.origin
// import * as AiHumanPMSDK from "./scripts/AiHumanPM_v1.3.0.js"

const props = defineProps({
  x: {
    default: '0'
  },
  y: {
    default: '0'
  },
  width: {
    default: '384'
  },
  height: {
    default: '432'
  },
  opacity: {
    default: '1'
  },
  ueUrl: {
    type: String,
    default: null
  },
  ueStreamerId: {
    type: String,
    default: null
  },
})

// let ueWebSocket = new driveUeWebsocket();
async function driveUe(dataParams) {

    /*女生出场*/
    const startData = {
      "type": 7,
      "data": {
        "speech": {
          "genType": "2",
          "ttsInfo": {
            "text": dataParams,
            "ssml": "<speak xmlns=\"http://www.w3.org/2001/10/synthesis\" version=\"1.0\" xml:lang=\"zh-CN\"><voice name=\"zh-CN-XiaoxiaoNeural\"  xml:gender=\"male\" xml:lang=\"zh-CN\"><prosody rate=\"1\" volum=\"100\">" + dataParams + "</prosody></voice></speak>"
          }
        },
        "modelActions": [
          {
            "actionId": "Idle_2",
            "startTime": "00:00:01:000",
            "endTime": "00:00:00:000",
          },
          {
            "actionId": "F-52",
            "startTime": "00:00:03:000",
            "endTime": "00:00:00:000",
          },
          {
            "actionId": "F-83",
            "startTime": "00:00:10:000",
            "endTime": "00:00:00:000",
          },
          {
            "actionId": "F-95",
            "startTime": "00:00:18:000",
            "endTime": "00:00:00:000",
          },
          {
            "actionId": "F-50",
            "startTime": "00:00:24:000",
            "endTime": "00:00:00:000",
          },
          {
            "actionId": "Idle_3",
            "startTime": "00:00:29:000",
            "endTime": "00:00:00:000",
          },
        ],
        "nodeTime": 31
      }
    }

    if (window.AiHumanPMSDK.AiHumanIsReady) {
      // ueWebSocket.sendEventFromOut(startData)
      // await driveUeApi(startData).then((res) => {
      //   console.log('res', res);

      // });
    } else {

    }
}
var width;
var height;
var ueUrl;
var ueStreamerId;
onMounted(async () => {

  if(AiHumanPMConfig){
    width = props.width;
    height = props.height;
    ueUrl = props.ueUrl;
    ueStreamerId = props.ueStreamerId;
    AiHumanPMConfig = {
        // AiHumanUse: true, 
        // AiHumanShowUseBtn: false,
        // AiHumanWidth: parseFloat(props.width),
        // AiHumanHeight: parseFloat(props.height),
        // // ss: "wss://127.0.0.1:10443",
        // ss: "https://aihuman.huilan.com:10443/",
        // AutoConnect: false,
        preConnect: true, //预连接 成功后显示播放按钮
        preConnectTimes: 10, //预连接  重连最大次数
        AiHumanUse: true, 
        AiHumanShowUseBtn: false,
        AiHumanWidth: parseFloat(width),
        AiHumanHeight: parseFloat(height),
        ss: ueUrl,
        // ss: "wss://"+window.location.hostname+":"+window.location.port+"/streamApi/",
        StreamerId: ueStreamerId, // 一定不能设置为 defaultAiHumanPMSDKId 
        noInStreamerListUseFirst: false,  //StreamerId没有时 调用已有的第一个
        // AFKTimeout: 600,
        AutoConnect: false, //想自动加载  AutoConnect AutoPlayVideo StartVideoMuted 三项必须同时为true 但会被静音  或者改浏览器设置
        // StartVideoMuted: false,
        // AutoPlayVideo: true,
         // OfferToReceive: false,
        // KeyboardInput: false,
        // MouseInput: false,
        // TouchInput: false,
        // GamepadInput: false,
        // XRControllerInput: false,
        // WaitForStreamer: false,

      };
  }
  
      
  // 创建一个新的script标签
  var script = document.createElement('script');
  // 设置script标签的src属性为要引入的JavaScript文件的URL
  script.src = origin+'/aihumanShow/scripts/AiHumanPM_LatestVersion.js';
  
  // script.src = new URL(`./scripts/AiHumanPM_LatestVersion.js`, import.meta.url).href
  // 将script标签添加到页面的head部分或者其他合适的位置
  document.head.appendChild(script);
  script.onload = function() {
    console.log('AiHumanPMSDK', window.AiHumanPMSDK);
    // document.getElementById('AiHumanPlayBtn').style.display = 'none';
    // window.AiHumanPMSDK.AiHumanStream.addEventListener('webRtcConnected', () => {
    //     // console.log('webRtcConnected');
    //     // if(document.getElementById('AiHumanPlayBtn')){
    //     //   document.getElementById('AiHumanPlayBtn').style.display = 'block';
    //     // }
        
    //     // clearInterval(inter);
    //     emitter.emit(mittTypes.LOADING.LOAD_FINISH)
    //   });
      // window.AiHumanPMSDK.AiHumanStream.connect();
    let inter = setInterval(() => {
     if(document.getElementById('AiHumanPlayBtn')){
          emitter.emit(mittTypes.LOADING.LOAD_FINISH)
          clearInterval(inter);
          document.getElementById('AiHumanPlayBtn').click();
          window.parent.postMessage({
                    type: 'setIframePointerEvents',
                    value: 'none'
                  }, '*');
          // document.getElementById('streamingVideo').onplay = function() {
          //   console.log('视频播放');
          //   // 当前窗口作为iframe嵌入时，设置当前窗口的pointer-events为none
          //   if (window.self !== window.top) {
          //     // 检测当前窗口是否在iframe中
          //     window.parent.postMessage({
          //           type: 'setIframePointerEvents',
          //           value: 'none'
          //         }, '*');
          //   }
          // }
          // document.getElementById('AiHumanPlayBtn').style.display = 'block';
        }
    }, 1000);
       
  }
  // setTimeout(() => {
  //   // document.getElementById('AiHumanPlayBtn').style.display = 'none';
  //   window.AiHumanPMSDK.AiHumanStream.connect();
  //   // window.AiHumanPMSDK.AiHumanStream.addEventListener('webRtcConnected', () => {
  //   //   // console.log('webRtcConnected');
  //   //   document.getElementById('AiHumanPlayBtn').style.display = 'block';
  //   // });
  // }, 4000);
  
  
  // ueWebSocket.StartStreamer('ws://localhost:8080/')

  emitter.on(mittTypes.LIVEKIT.MESSAGE_CHAT_RECIVE,function(data){
    let messageData = data.messageData;
    let from = data.from;
    switch(from){
      case mittTypes.LIVEKIT.MESSAGE_CHAT_FROM_TYPE.BOT:
        driveUe(messageData.message)
        break;
      case mittTypes.LIVEKIT.MESSAGE_CHAT_FROM_TYPE.LOCAL:
        
    }
    
  })
  emitter.on(mittTypes.TIMELINE.MUTE_AUDIO,function(){
    document.getElementById("streamingVideo").muted = true;
  })
  emitter.on(mittTypes.TIMELINE.UNMUTE_AUDIO,function(){
    document.getElementById("streamingVideo").muted = false;
  })
})
</script>
<script lang="ts">
export default {
  name: 'AiHumanUeRenderer'
}
</script>
<style scoped>
    .AiHumanPM { position: absolute; top: 0px; left: 0px;right: 0;bottom: 0;margin: auto; }
    .AiHumanPushMaskStream .AiHumanPlayBtn { position: fixed; left: 90px; display: none;}

</style>